package com.five.filesync;

import android.os.AsyncTask;
import android.util.Log;

import com.five.filesync.bean.FileCacheListRespondBean;
import com.five.filesync.bean.FileListRespondBean;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.InetAddress;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FileCacheListRequest extends AsyncTask<String, Void, Boolean> {
    private static final String TAG = "FileCacheListRequest";

    private static final boolean USE_CACHE = true;

    private String url;
    private String dirname;
    private String filename;
    private OnNetCallback callback;
    public FileCacheListRequest(InetAddress host, int port, String dirname, String filename, OnNetCallback callback) {
        this.url = String.format("http://%s:%s/getFileCacheList/%s/%s", host.getHostAddress(), port, dirname, filename);
        this.dirname = dirname;
        this.filename = filename;
        this.callback = callback;
    }

    @Override
    protected Boolean doInBackground(String... fileUrl) {

        OkHttpClient client = new OkHttpClient();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 发送请求
        try {
            Response response = client.newCall(request).execute();

            // 处理响应
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                Gson gson = new Gson();
                FileCacheListRespondBean bean = gson.fromJson(responseBody, FileCacheListRespondBean.class);
                if (bean.getStatus() != 0) {
                    // ok
                    Log.d(TAG, String.format("get file cache list successfully! url=%s", url));
                    extraInfo = bean.getList();
                    return true;
                } else {
                    Log.d(TAG, String.format("get file cache list failed! url=%s, msg=%s", url, bean.getErr()));
                }
            } else {
                Log.d(TAG, String.format("get file cache failed! url=%s, localFile=%s", url, ""));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e(TAG, String.format("download %s failed", url));
        return false;
    }

    private Object extraInfo;
    @Override
    protected void onPostExecute(Boolean ret) {
        if (this.callback != null) {
            this.callback.onResult(ret, extraInfo);
        }
    }
}